package com.sts.common.exception;

import com.sts.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /** 参数校验失败 */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Result<Map<String, String>> validException(Exception ex) {
        Map<String, String> errors = new HashMap<>();
        var br = ex instanceof MethodArgumentNotValidException
                ? ((MethodArgumentNotValidException) ex).getBindingResult()
                : ((BindException) ex).getBindingResult();
        br.getFieldErrors().forEach(fe -> errors.put(fe.getField(), fe.getDefaultMessage()));
        return Result.error("参数校验失败", errors).code(HttpStatus.BAD_REQUEST.value());
    }

    /** 业务异常 */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BusinessException.class)
    public Result<Object> business(BusinessException e) {
        return Result.error(e.getMessage()).code(e.getCode());
    }

    /** 兜底：所有未捕获异常 */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<Object> others(Exception e) {
        log.error("系统异常", e);
        return Result.error("系统繁忙，请稍后重试")
                .code(HttpStatus.INTERNAL_SERVER_ERROR.value());
    }
}